package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserSservice;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserSservice userSservice;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody  User user, HttpSession httpSession){
        String phone=user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code= ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            httpSession.setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }
    //移动端客户登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession httpSession){
        String phone=map.get("phone").toString();
        String code=map.get("code").toString();
        String codeSessiom=httpSession.getAttribute(phone).toString();

        if(codeSessiom.equals(code)){
            LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user=userSservice.getOne(wrapper);
            if(user==null){
                user=new User();
                user.setPhone(phone);
                userSservice.save(user);
//                user1.setName("用户"+codeSessiom);
            }
            httpSession.setAttribute("user",user.getId());
            //并将其作为结果返回
            return R.success(user);
        }
        return R.error("短信发送失败");
    }
}
